package com.project.controller;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageInfo;
import com.project.bean.OrderBean;
import com.project.bean.UserBean;
import com.project.service.IOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.time.LocalDate;
import java.util.List;

/**
 * 结账
 */
@RestController
@RequestMapping("order")
public class OrderController {
    @Autowired
    private IOrderService orderService;

    @RequestMapping("add")
    public String add(@Valid OrderBean order,BindingResult result, HttpServletRequest request) throws Exception {
        System.out.println("``````````````````````");
        System.out.println(result.hasErrors());
        if (result.hasErrors()){//判断是否有出错信息
            //取出出错信息
            List<FieldError>errorList =result.getFieldErrors();
            String str = new ObjectMapper().writeValueAsString(errorList);
            return str;
        }
        UserBean user = (UserBean)request.getSession().getAttribute("loginUser");
        orderService.add(order, user.getId());
        return "ok";
    }

    @RequestMapping("findByItemStatus")
    public List<OrderBean>findByItemStatus(){
        return orderService.findByItemStatus();
    }

    @RequestMapping("send")
    public String send(int id){
        orderService.send(id);
        return "ok";
    }

    @RequestMapping("finish")
    public String finish(int id){
        orderService.finish(id);
        return "ok";
    }

    @RequestMapping("findByItem")
    public PageInfo<OrderBean> findByItem(int pageNo, String status,
                                          LocalDate startDate, LocalDate endDate,
                                          Integer userId){
        PageInfo<OrderBean>pageInfo=orderService.findByItem(pageNo, status, startDate, endDate, null);
        return pageInfo;
    }

    @RequestMapping("findById")
    public OrderBean findById(int id){
        return orderService.findById(id);
    }
}
